﻿using RBACDemo.Domain.UserInfo;
using Youshow.Ace.Domain.Repository;
using Youshow.Ace.Domain.Services;

namespace RBACDemo.Domain.Managers;

public class UserManager(
    IRepository<User> userRepository,
    IRepository<Role> roleRepository,
    IRepository<UserRoleMapping> userRoleMappingRepository) : DomainServicer
{
    // public IRepository<User> UserRepository { get; set; }
    // public IRepository<Role> RoleRepository { get; set; }

    /// <summary>
    ///  获取用户信息的同时获取其角色信息
    /// </summary>
    /// <param name="ids">用户Id集合</param>
    /// <returns></returns>
    public async Task<List<User>> GetUserAsync(params long[] ids)
    {
        var users = await userRepository.GetListAsync(m => ids.Contains(m.Id));
        users = await roleRepository.WithJoinAsync<UserRoleMapping, User>(
            users,
            m => m.Roles
        );
        return users;
    }
    
    /// <summary>
    ///  根据userId删除UserRoleMapping表中的数据
    /// </summary>
    /// <param name="userId">用户Id</param>
    public async Task DeleteUserRoleAsync(long userId)
    {
        await userRoleMappingRepository.DeleteAsync(m => m.UserId == userId);
    }

    /// <summary>
    ///  根据userId、roleIds给用户添加相应的角色，保存在UserRoleMapping表中
    /// </summary>
    /// <param name="userId">用户Id</param>
    /// <param name="roleIds">角色Id集合</param>
    public async Task AddUserRoleAsync(long userId, List<long> roleIds)
    {
        List<UserRoleMapping> userRoleMappings = new();
        roleIds.ForEach(m =>
        {
            userRoleMappings.Add(new UserRoleMapping()
            {
                UserId = userId,
                RoleId = m
            });
        });
        await userRoleMappingRepository.InsertManyAsync(userRoleMappings, false);
    }
    
    
}